#include "fun.h"
#include "iic.h"

u8 bdata LED = 0x01;
sbit L1 = LED^0;
sbit L2 = LED^1;
sbit L3 = LED^2;
sbit L4 = LED^3;
sbit L5 = LED^4;
u8 i = 0,t_100ms = 1;
u16 u_dat;
u16 f = 0;
u8 code t_display[]={                       //标准字库
//   0    1    2    3    4    5    6    7    8    9    
    0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,
    0xBF,0x86,0xDB,0xCF,0xE6,0xED,0xFD,0x87,0xFF,0xEF,0x71,0x3E,0x00};   
//   0.   1.   2.    3.   4.   5.   6.   7.   8.   9.   F    U    

u8 code T_COM[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};      //位码
u8 data_disp[][8] = 
{
    {21,22,22,22,22,0,0,0},
    {20,22,22,0,0,0,0,0}
};


void Timer2Init(void)		//1毫秒@12.000MHz
{
	AUXR |= 0x04;		//定时器时钟1T模式
	T2L = 0x20;		//设置定时初值
	T2H = 0xD1;		//设置定时初值
	AUXR |= 0x10;		//定时器2开始计时
    IE2 |= 0x04;
    EA = 1;
}

void smg_pro(void)
{
    if(!ui_status)
    {
        data_disp[0][5] = (u_dat / 100) + 10;
        data_disp[0][6] = (u_dat % 100) / 10;
        data_disp[0][7] = u_dat % 10;
    }
    else
    {
        data_disp[1][2] = 22;
        data_disp[1][3] = (f >= 10000)?(f / 10000):22;
        data_disp[1][4] = (f >= 1000)?((f % 10000) / 1000):22;
        data_disp[1][5] = (f >= 100)?((f % 1000) / 100):22;
        data_disp[1][6] = (f >= 10)?((f % 100) / 10):22;
        data_disp[1][7] = f % 10;
    }
}

void led_pro(void)
{
    if(!ui_status)
        L1 = 1,L2 = 0;
    else
        L1 = 0,L2 = 1;
    
    if(u_dat < 150 || (u_dat >= 250 && u_dat < 350))
        L3 = 0;
    else if((u_dat >= 150 && u_dat < 250) || u_dat >= 350)
        L3 = 1;
    
    if(f < 1000 || (f >= 5000 && f < 10000))
        L4 = 0;
    else if((f >= 1000 && f < 5000) || f >= 10000)
        L4 = 1;

    if(!out_mode)
        L5 = 0;
    else
        L5 = 1;
}

void main(void)
{
    u8 temp;
    buzzer(0);
    relay(0);
    led(LED);
    Timer2Init();
    TMOD |= 0x04;   //定时器0做计数器
    TR0 = 1;
    
    while(1)
    {
        if(t_100ms)
        {
            t_100ms = 0;
            temp = read_adc();
            u_dat = (temp/255.0) * 500;
            
            if(!out_mode && mode_update)
			{
				dac_out(102); 
				mode_update = 0;
			}
            else if(out_mode)
				dac_out(temp);	
        }
        
        smg_pro();
        led_pro();
    }
}

void t2_callback(void) interrupt 12
{
    static u8 t = 0,key_count = 0;
    static u16 f_count = 0;
    if(++t == 100)
        t_100ms = 1;
    if(++key_count == 10)
    {
        key_scan();
        key_count = 0;
    }

    if(++f_count == 1000)
    {
        f_count = 0;
        TR0 = 0;
        f = (TH0 << 8) | TL0;
        TL0 = 0;TH0 = 0;
        TR0 = 1; 
    }

    if(led_flag)
        led(LED);
    else
        led(0x00);

    i %= 8;
    if(smg_flag)
        smg_disp(t_display[data_disp[ui_status][i]],T_COM[i]);
    i++;
}
